"""
AI工具集数据库模型
"""

from datetime import datetime
from typing import Optional, List, Dict, Any

from sqlalchemy import String, Text, Integer, DateTime, SmallInteger, Index
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func

from config.database import Base


class AIWebToolsModel(Base):
    """AI工具集数据库模型"""
    __tablename__ = "ai_web_tools"

    # 主键
    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键ID")

    # 基本字段
    category_name: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        unique=True,
        comment="工具类名称"
    )
    category_code: Mapped[str] = mapped_column(
        String(50),
        nullable=False,
        unique=True,
        comment="工具类代码，唯一标识"
    )
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True, comment="工具类介绍")
    is_enabled: Mapped[int] = mapped_column(
        SmallInteger,
        nullable=False,
        default=1,
        comment="工具类是否可用(1=可用,0=禁用)"
    )

    # 时间字段
    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        nullable=False,
        default=func.current_timestamp(),
        comment="创建时间"
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        nullable=False,
        default=func.current_timestamp(),
        onupdate=func.current_timestamp(),
        comment="更新时间"
    )

    # 索引和约束
    __table_args__ = (
        Index('idx_category_name', 'category_name'),
        Index('idx_category_code', 'category_code'),
        Index('idx_is_enabled', 'is_enabled'),
        {"comment": "AI工具集管理表"}
    )

    def __repr__(self):
        return f"<AIWebToolsModel(id={self.id}, category_name='{self.category_name}', category_code='{self.category_code}', is_enabled={self.is_enabled})>"

    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "id": self.id,
            "category_name": self.category_name,
            "category_code": self.category_code,
            "description": self.description,
            "is_enabled": self.is_enabled,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }

    def is_active(self) -> bool:
        """判断工具集是否处于可用状态"""
        return self.is_enabled == 1

    def is_disabled(self) -> bool:
        """判断工具集是否处于禁用状态"""
        return self.is_enabled == 0

    def enable(self) -> None:
        """启用工具集"""
        self.is_enabled = 1
        self.updated_at = datetime.now()

    def disable(self) -> None:
        """禁用工具集"""
        self.is_enabled = 0
        self.updated_at = datetime.now()

    def update_status(self, new_status: int) -> None:
        """更新工具集状态"""
        # 验证status值
        if not isinstance(new_status, int):
            # 如果传入的是字符串，尝试转换
            if isinstance(new_status, str):
                try:
                    new_status = int(new_status)
                except ValueError:
                    raise ValueError(f"无效的状态值: {new_status}，必须是 0, 1 中的一个")
            elif isinstance(new_status, bool):
                new_status = 1 if new_status else 0
            else:
                raise ValueError(f"状态值必须是整数或布尔值，当前类型: {type(new_status)}")

        if new_status not in [0, 1]:
            raise ValueError(f"无效的状态值: {new_status}，必须是 0, 1 中的一个")

        self.is_enabled = new_status
        self.updated_at = datetime.now()

    def get_tools_count(self) -> int:
        """获取工具数量（已废弃，因为移除了关系）"""
        return 0

    def get_enabled_tools_count(self) -> int:
        """获取启用的工具数量（已废弃，因为移除了关系）"""
        return 0

    def get_tool_names(self) -> List[str]:
        """获取所有工具名称列表（已废弃，因为移除了关系）"""
        return []

    def get_enabled_tool_names(self) -> List[str]:
        """获取启用的工具名称列表（已废弃，因为移除了关系）"""
        return []

    def find_tool_by_name(self, tool_name: str):
        """根据工具名称查找工具（已废弃，因为移除了关系）"""
        return None

    def get_tools_summary(self) -> Dict[str, Any]:
        """获取工具集摘要信息"""
        return {
            "category_name": self.category_name,
            "description": self.description,
            "is_enabled": self.is_enabled,
            "total_tools": self.get_tools_count(),
            "enabled_tools": self.get_enabled_tools_count(),
            "tool_names": self.get_tool_names(),
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }

    def clone_config(self) -> Dict[str, Any]:
        """克隆工具配置（用于复制工具集）"""
        return {
            "category_name": f"{self.category_name}_copy",
            "description": self.description,
            "is_enabled": self.is_enabled
        }
